package org.model.data;

//import java.util.Vector;
import net.wimpi.modbus.msg.ReadInputRegistersRequest;
import net.wimpi.modbus.msg.ReadInputRegistersResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import org.model.modbus.GSMModbusSerialTransaction;
import org.util.Util;


/**
 *
 * @author German Garcia
 */
public class Device {
    public static final String GSM = "GSM";
    public static final String RISH = "RISH";
    public static final String GLES_V1 = "GLES 1.0";
    public static final String GLES_V2 = "GLES 2.0";

    private String id;
    private String name;
    private int type;
    private String reference;

    // Used for modbus communications
    private ReadInputRegistersResponse readInputRegistersResponse = new ReadInputRegistersResponse();
    private ReadMultipleRegistersResponse readMultipleRegistersResponse = new ReadMultipleRegistersResponse();
    private ReadMultipleRegistersRequest readMultipleRegistersRequest = new ReadMultipleRegistersRequest();
    private ReadInputRegistersRequest readInputRegistersRequest = new ReadInputRegistersRequest();

    public Device() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getReference() {
        return reference;
    }

    public void setReference(String reference) {
        this.reference = reference;
    }

    public String getAsString() {
        return id+","+name+","+type+","+reference;
    }

    public String toString() {
        return id+": "+name+" ["+reference+"]";
    }

    /* Metodos para GLES */
    public String readConfiguration(String datetime, GSMModbusSerialTransaction serialTransaction) {
        String dataFrame = id + "," + "GLES" + "," + datetime;
        String errors = "ERROR";
        int blocksReaded = 0;
        int unitid = Integer.parseInt(id); //Integer.parseInt(id);

        	int ref = 0;
        int count = 0;
        try {
            // Parametros del GLES
            ref = 35;
            count = 20;
            readMultipleRegisters(ref, count, unitid, serialTransaction);
            dataFrame = dataFrame + "," + getData();

            ref = 55;
            count = 13;
            readMultipleRegisters(ref, count, unitid, serialTransaction);
            dataFrame = dataFrame + "," + getData();

            ref = 127;
            count = 4;
            readMultipleRegisters(ref, count, unitid, serialTransaction);
            dataFrame = dataFrame + "," + getData();
            blocksReaded++;
        } catch(Exception ex) {
            //ErrorLogger.log(gles, "An error occured while capturing gles data.", ex);
            errors = "An error occured while capturing gles " + name + " data.";
        }
        if(blocksReaded>0) return dataFrame;
        return "error," + errors;
    }

    public boolean writeConfiguration(String data, GSMModbusSerialTransaction serialTransaction) {
        try {
            //System.out.println("Actualizando el Gles ID " + id);
            int ref = 0;
            int writeval = 0;
            int unitid = Integer.parseInt(id); //Integer.parseInt(id);
            String values[] = Util.split(data,",");

            ref = 42; // Start_Mode
            writeval = Integer.parseInt(values[7]); //Integer.parseInt(values[7]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 41; // Status
            writeval = Integer.parseInt(values[6]); //Integer.parseInt(values[6]);
            Thread.sleep(3000);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Status Parameter.", ex);
            }

            ref = 43; // Auto_Start_Min
            writeval = Integer.parseInt(Util.split(values[8],":")[1]);
            Thread.sleep(5000);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Auto_Start_Min Parameter.", ex);
            }

            ref = 44; // Auto_Start_Hor
            writeval = Integer.parseInt(Util.split(values[8],":")[0]);
            Thread.sleep(350);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Auto_Start_Hor Parameter.", ex);
            }

            ref = 45; // Auto_Stop_Min
            writeval = Integer.parseInt(Util.split(values[9],":")[1]);
            Thread.sleep(350);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Auto_Stop_Min Parameter.", ex);
            }

            ref = 46; // Auto_Stop_Hor
            writeval = Integer.parseInt(Util.split(values[9],":")[0]);
            Thread.sleep(350);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Auto_Stop_Hor Parameter.", ex);
            }

            ref = 47; // Save1_Start_Min
            writeval = Integer.parseInt(Util.split(values[10],":")[1]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 48; // Save1_Start_Hor
            writeval = Integer.parseInt(Util.split(values[10],":")[0]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 49; // Save1_Stop_Min
            writeval = Integer.parseInt(Util.split(values[11],":")[1]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 50; // Save1_Stop_Hor
            writeval = Integer.parseInt(Util.split(values[11],":")[0]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 51; // Save2_Stop_Min
            writeval = Integer.parseInt(Util.split(values[12],":")[1]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 52; // Save2_Stop_Hor
            writeval = Integer.parseInt(Util.split(values[12],":")[0]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 53; // Save3_Stop_Min
            writeval = Integer.parseInt(Util.split(values[13],":")[1]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 54; // Save3_Stop_Hor
            writeval = Integer.parseInt(Util.split(values[13],"-")[0]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 55; // VOut1_Window
            writeval = Integer.parseInt(values[14]);
            Thread.sleep(450);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 56; // VOut2_Window
            writeval = Integer.parseInt(values[15]);
            Thread.sleep(450);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 57; // VOut3_Window
            writeval = Integer.parseInt(values[16]);
            Thread.sleep(450);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 58; // VOut4_Window
            writeval = Integer.parseInt(values[17]);
            Thread.sleep(450);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 61; // kwh_año
            writeval = Integer.parseInt(Util.split(values[18],"-")[0]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 60; // kwh_mes
            writeval = Integer.parseInt(Util.split(values[18],"-")[1]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 59; // kwh_dia
            writeval = Integer.parseInt(Util.split(values[18],"-")[2]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 62; // Astro_Adjust1
            writeval = Integer.parseInt(values[19]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 63; // Astro_Adjust2
            writeval = Integer.parseInt(values[20]);
            Thread.sleep(350);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 64; // Config_Ignition_Time
            writeval = Integer.parseInt(values[21]);
            Thread.sleep(450);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Config_Ignition_Time Parameter.", ex);
            }

            ref = 65; // Reduction_Rate_Screen
            writeval = Integer.parseInt(values[22]);
            Thread.sleep(450);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Reduction_Rate_Screen Parameter.", ex);
            }

            ref = 66; // Config_Current_Screen
            writeval = Integer.parseInt(values[23]);
            Thread.sleep(450);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Config_Current_Screen Parameter.", ex);
            }

            ref = 67; // Config_Net_Voltage
            writeval = Integer.parseInt(values[24]);
            Thread.sleep(450);
            try {
                tryToWriteIn(ref, unitid, writeval, serialTransaction);
            } catch(Exception ex) {
                //ErrorLogger.log(gles, "An error occured while writing Config_Net_Voltage Parameter.", ex);
            }

            ref = 127; // Current_Detect_Screen
            writeval = Integer.parseInt(values[25]);
            Thread.sleep(450);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 128; // Current_Step_Screen
            writeval = Integer.parseInt(values[26]);
            Thread.sleep(450);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 129; // Service_Screen
            writeval = Integer.parseInt(values[27]);
            Thread.sleep(650);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            ref = 130; // Lock_Parameter_Screen
            writeval = Integer.parseInt(values[28]);
            Thread.sleep(650);
            tryToWriteIn(ref, unitid, writeval, serialTransaction);

            Thread.sleep(15000);
            //this.wait(15000);
        } catch(Exception ex) {
            //ErrorLogger.log(gles, "An error occured while trying to write configuration data to specified gles id.", ex);
        }
        return false;
    }

    /* Metodos para METER GSM*/
    public String readGSMParameters(String datetime, GSMModbusSerialTransaction serialTransaction) {
        boolean offline = false;
        String dataFrame = id + "," + "METERGSM" + "," + datetime;
        String errors = "ERROR";
        int blocksReaded = 0;
        int unitid = Integer.parseInt(id); //Integer.parseInt(id);
        int ref = 0;
        int count = 0;
        try {
            // Parametros del MEDIDOR
            // Lectura de: Volts1, Volts2, Volts3, Current1, Current2, Current3
            // Lectura de: W1, W2, W3, VA1, VA2, VA3
            // Lectura de: VAR1, VAR2, VAR3, PF1, PF2, PF3
            // Lectura de: Phase Angle1, Phase Angle2
            ref = 0;
            count = 40;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 20);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0";
                offline = true;
                //ErrorLogger.log(meter, "An error occured while capturing Volts, Currents, Watts, VAs, VARs, PFs And PhAngs", ex);
            }

            // Lectura de: Phase Angle3, Volts Avg, Volts Sum, Current Avg, Current Sum
            // Lectura de: Watts Avg, Watts Sum, VA Avg, VA Sum, VAr Avg, VAr Sum
            // Lectura de: PF Avg, PF Sum, Phase Angle Avg, Phase Angle Sum
            // Lectura de: Freq, Wh Import, Wh Export, VARh Import, VARh Export
            if(offline) dataFrame = dataFrame + ",0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0";
            else {
                ref = 40;
                count = 40;
                try {
                    readInputRegisters(ref, count, unitid, serialTransaction);
                    dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 20);
                    blocksReaded++;
                } catch(Exception ex) {
                    dataFrame = dataFrame + ",0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0";
                    //ErrorLogger.log(meter, "An error occured while capturing Phase Angle3, Avgs, Sums, Freq, Wh Import, Wh Export, VARh Import And VARh Export", ex);
                }
            }

            // Lectura de: VAh
            if(offline) dataFrame = dataFrame + ",0.0";
            else {
                ref = 80;
                count = 2;
                try {
                    readInputRegisters(ref, count, unitid, serialTransaction);
                    dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                    blocksReaded++;
                } catch(Exception ex) {
                    dataFrame = dataFrame + ",0.0";
                    //ErrorLogger.log(meter, "An error occured while capturing VAh.", ex);
                }
            }

            // Lectura de: Volts Avg Max, Volts Avg Min
            if(offline) dataFrame = dataFrame + ",0.0,0.0";
            else {
                ref = 132;
                count = 4;
                try {
                    readInputRegisters(ref, count, unitid, serialTransaction);
                    dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 2);
                    blocksReaded++;
                } catch(Exception ex) {
                    dataFrame = dataFrame + ",0.0,0.0";
                    //ErrorLogger.log(meter, "An error occured while capturing Volts Avg Max And Volts Avg Min", ex);
                }
            }

            // Lectura de: Current Avg Max, Current Avg Min
            if(offline) dataFrame = dataFrame + ",0.0,0.0";
            else {
                ref = 140;
                count = 4;
                try {
                    readInputRegisters(ref, count, unitid, serialTransaction);
                    dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 2);
                    blocksReaded++;
                } catch(Exception ex) {
                    dataFrame = dataFrame + ",0.0,0.0";
                    //ErrorLogger.log(meter, "An error occured while capturing Current Avg Max And Current Avg Min", ex);
                }
            }

            // Lectura de: Volts L1-L2, Volt L2-L1, Volt L3-L1
            if(offline) dataFrame = dataFrame + ",0.0,0.0,0.0";
            else {
                ref = 200;
                count = 6;
                try {
                    readInputRegisters(ref, count, unitid, serialTransaction);
                    dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 3);
                    blocksReaded++;
                } catch(Exception ex) {
                    dataFrame = dataFrame + ",0.0,0.0,0.0";
                    //ErrorLogger.log(meter, "An error occured while capturing Volts L1-L2, L2-L3, L3-L1.", ex);
                }
            }

            // Lectura de: Neutral Current
            if(offline) dataFrame = dataFrame + ",0.0";
            else {
                ref = 224;
                count = 2;
                try {
                    readInputRegisters(ref, count, unitid, serialTransaction);
                    dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                    blocksReaded++;
                } catch(Exception ex) {
                    dataFrame = dataFrame + ",0.0";
                    //ErrorLogger.log(meter, "An error occured while capturing Neutral Current.", ex);
                }
            }

            // Lectura de: System Power
            if(offline) dataFrame = dataFrame + ",0.0";
            else {
                ref = 36;
                count = 2;
                try {
                    readMultipleRegisters(ref, count, unitid, serialTransaction);
                    dataFrame = dataFrame + "," + getValues(readMultipleRegistersResponse.getHexMessage(), 1);
                    blocksReaded++;
                } catch(Exception ex) {
                    dataFrame = dataFrame + ",0.0";
                    //ErrorLogger.log(meter, "An error occured while capturing System Power.", ex);
                }
            }
        } catch(Exception ex) {
            //ErrorLogger.log(meter, "An error occured while capturing meter data.", ex);
            errors = "An error occured while capturing meter " + name + " data.";
        }
        if(blocksReaded>0) return dataFrame;
        return "error," + errors;
    }

    /* Metodos para METER RISH */
    public String readRISHParameters(String datetime, GSMModbusSerialTransaction serialTransaction) {
        String dataFrame =id + "," + "METER" + "," + datetime;
        String errors = "ERROR";
        int blocksReaded = 0;
        int unitid = Integer.parseInt(id); //Integer.parseInt(id);
        int ref = 0;
        int count = 0;
        try {
            // Parametros del MEDIDOR
            // Lectura de: Volts1, Volts2, Volts3, Current1, Current2, Current3
            ref = 0;
            count = 12;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 6);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0,0.0,0.0,0.0,0.0,0.0";
                //ErrorLogger.log(meter, "An error occured while capturing Volts And Currents", ex);
            }

            // Lectura de: VoltsAvg
            ref = 42;
            count = 2;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing Volts Avg.", ex);
            }

            // Lectura de: CurrentAvg
            ref = 46;
            count = 2;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing Currents Avg.", ex);
            }

            // Lectura de: WattsSum
            ref = 52;
            count = 2;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing Watts Sum.", ex);
            }

            // Lectura de: VASum
            ref = 56;
            count = 2;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing VA Sum.", ex);
            }

            // Lectura de: VArSum
            ref = 60;
            count = 2;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing VAr Sum.", ex);
            }

            // Lectura de: Power Factor Avg
            ref = 62;
            count = 2;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing PF Avg.", ex);
            }

            // Lectura de: Frequency, WhImport
            ref = 70;
            count = 4;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 2);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0,0.0";
                //ErrorLogger.log(meter, "An error occured while capturing Freq. And Wh Import.", ex);
            }

            // Lectura de: VarhImport
            ref = 76;
            count = 2;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing VArh Import.", ex);
            }

            // Lectura de: W Demand Import, W Max. Demand Import
            ref = 84;
            count = 4;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 2);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0,0.0";
                //ErrorLogger.log(meter, "An error occured while capturing W Demand Import And W Max Demand Import.", ex);
            }

            // Lectura de: A Demand, A Max. Demand
            ref = 104;
            count = 4;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 2);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0,0.0";
                //ErrorLogger.log(meter, "An error occured while capturing A Demand And A Max Demand.", ex);
            }

            // Lectura de: Volt L1-L2, Volt L2-L1, Volt L3-L1
            ref = 200;
            count = 6;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 3);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0,0.0,0.0";
                //ErrorLogger.log(meter, "An error occured while capturing Volts L1-L2, L2-L3, L3-L1.", ex);
            }

            // Lectura de: Neutral Current
            ref = 224;
            count = 2;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing Neutral Current.", ex);
            }

            // Lectura de: THD Volts1, THD Volts2, THD Volts3,
            //             THD Current1, THD Current2, THD Current3,
            ref = 234;
            count = 12;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 6);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0,0.0,0.0,0.0,0.0,0.0";
                //ErrorLogger.log(meter, "An error occured while capturing THD Volts And Current.", ex);
            }

            // Lectura de: THD Voltage Mean, THD Current Mean
            ref = 248;
            count = 4;
            try {
                readInputRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readInputRegistersResponse.getHexMessage(), 2);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0,0.0";
                //ErrorLogger.log(meter, "An error occured while capturing THD Means.", ex);
            }

            // Lectura de: System Power
            ref = 36;
            count = 2;
            try {
                readMultipleRegisters(ref, count, unitid, serialTransaction);
                dataFrame = dataFrame + "," + getValues(readMultipleRegistersResponse.getHexMessage(), 1);
                blocksReaded++;
            } catch(Exception ex) {
                dataFrame = dataFrame + ",0.0";
                //ErrorLogger.log(meter, "An error occured while capturing System Power.", ex);
            }
        } catch(Exception ex) {
            //ErrorLogger.log(meter, "An error occured while capturing meter data.", ex);
            errors = "An error occured while capturing meter " + name + " data.";
        }
        if(blocksReaded>0) return dataFrame;
        return "error," + errors;
    }

    /* Metodos para comunicaciones MODBUS */
    private synchronized void writeSingleRegister(int ref, int unitid, int value, GSMModbusSerialTransaction serialTransaction) throws Exception {
        /*
        boolean done;
        ObservableRegister reg = new ObservableRegister();
        reg.setValue(value);
        WriteSingleRegisterRequest wsrrq = new WriteSingleRegisterRequest(ref, reg);
        wsrrq.setUnitID(unitid);
        wsrrq.setHeadless();
        //System.out.println("Write request: " + wsrrq.getHexMessage());

        //8. Execute the transaction
        modbusSerialTransaction.setRequest(wsrrq);
        done = false;
        try {
            modbusSerialTransaction.execute();
            done = true;
        } catch(Exception ex) {
            ErrorLogger.log(gles, "An error occured while sending write instruction to gles. First try.", ex);
        }
        if(!done) {
            try {
                //Thread.sleep(350);
                modbusSerialTransaction.execute();
            } catch(Exception ex) {
                ErrorLogger.log(gles, "An error occured while sending write instruction to gles. Second try.", ex);
            }
        }

        //9. Get the request answer and save it
        WriteSingleRegisterResponse wsrre = (WriteSingleRegisterResponse) modbusSerialTransaction.getResponse();
        //System.out.println("Write response: " + wsm.getHexMessage());
        //System.out.println("Answer Word = " + wsm.getRegisterValue());
        */
    }

    private synchronized void readMultipleRegisters(int ref, int count, int unitid, GSMModbusSerialTransaction serialTransaction) throws Exception {
        readMultipleRegistersRequest.setReference(ref);
        readMultipleRegistersRequest.setWordCount(count);
        readMultipleRegistersRequest.setUnitID(unitid);
        readMultipleRegistersRequest.setHeadless();
        //System.out.println("Request: " + readMultipleRegistersRequest.getHexMessage());
        // Execute the transaction
        serialTransaction.setRequest(readMultipleRegistersRequest);
        serialTransaction.execute();
        // Get the request answer
        readMultipleRegistersResponse = (ReadMultipleRegistersResponse) serialTransaction.getResponse();
        //System.out.println("Response: " + readMultipleRegistersResponse.getHexMessage());
    }

    private synchronized void readInputRegisters(int ref, int count, int unitid, GSMModbusSerialTransaction serialTransaction) throws Exception {
        readInputRegistersRequest.setReference(ref);
        readInputRegistersRequest.setWordCount(count);
        readInputRegistersRequest.setUnitID(unitid);
        readInputRegistersRequest.setHeadless();
        //System.out.println("Request: " + readInputRegistersRequest.getHexMessage());
        // Execute the transaction
        serialTransaction.setRequest(readInputRegistersRequest);
        System.out.println("725-Device...Request:"+readInputRegistersRequest.getHexMessage());
        serialTransaction.execute();
        // Get the request answers
        readInputRegistersResponse = (ReadInputRegistersResponse) serialTransaction.getResponse();
        System.out.println("729-Device...Response: '" + readInputRegistersResponse.getHexMessage() + "'");
    }

    private String getValues(String hexString, int count) {
        String svalue, retvalues;
        float value;
        retvalues = "";
        for(int i=0; i<count; i++) {
            svalue = hexString.substring(12*i +  9, 12*i + 11) +
                     hexString.substring(12*i + 12, 12*i + 14) +
                     hexString.substring(12*i + 15, 12*i + 17) +
                     hexString.substring(12*i + 18, 12*i + 20);
            value = getIEEEFloatValue(svalue);
            retvalues = retvalues+","+value;
        }
        //retvalues = retvalues.substring(1);
        return retvalues.substring(1);
    }

    private float getIEEEFloatValue(String value) {
        int b3 = (int)Long.parseLong(value.substring(0,2), 16);
        int b2 = (int)Long.parseLong(value.substring(2,4), 16);
        int b1 = (int)Long.parseLong(value.substring(4,6), 16);
        int b0 = (int)Long.parseLong(value.substring(6,8), 16);
        int b = b3<<24 | b2<<16 | b1<<8 | b0;
        return Float.intBitsToFloat(b); //Convert.toFloatBitwise(b);
    }

    private boolean tryToWriteIn(int ref, int unitid, int writeval, GSMModbusSerialTransaction serialTransaction) throws Exception {
        readMultipleRegisters(ref, 1, unitid, serialTransaction);
        //System.out.println("Received: " + readMultipleRegistersResponse.getHexMessage());
        String retval = getData();
        if(!retval.equalsIgnoreCase(writeval+"")) {
            Thread.sleep(350);
            writeSingleRegister(ref, unitid, writeval, serialTransaction);
            return true;
        }
        return false;
    }

    private String getData() {
        String retval = "";
        for(int i=0; i<readMultipleRegistersResponse.getWordCount()-1;i++) {
            //System.out.println("Word " + i + "=" + readMultipleRegistersResponse.getRegisterValue(i));
            retval = retval + readMultipleRegistersResponse.getRegisterValue(i) + ",";
        }
        retval = retval + readMultipleRegistersResponse.getRegisterValue(readMultipleRegistersResponse.getWordCount()-1);
        return retval;
    }    
}
